package com.example.yjhero.safeapp.activity;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.example.yjhero.safeapp.R;
import com.example.yjhero.safeapp.adapter.ContactAdapter;
import com.example.yjhero.safeapp.entities.ContactInfo;
import com.example.yjhero.safeapp.utils.ContactInfoParser;

import java.util.List;

public class ContactSelectActivity extends AppCompatActivity {
    private ListView mlistView;
    private ContactAdapter madapter;
    private List<ContactInfo> systemContacts;

    Handler mHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
           switch (msg.what){
               case 10:
                   if(systemContacts!=null){
                       madapter=new ContactAdapter(systemContacts,ContactSelectActivity.this);
                       mlistView.setAdapter(madapter);
                   }
                   break;
           }
        }
    };
private ImageView mLeftImagv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contact_select);
        initView();
        initData();
    }

    private void initData() {
       mLeftImagv.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               finish();
           }
       });

       new Thread(){
           @Override
           public void run() {
               systemContacts=ContactInfoParser.getSystemContact(ContactSelectActivity.this);
               systemContacts.addAll(ContactInfoParser.getSimContacts(ContactSelectActivity.this));
               mHandler.sendEmptyMessage(10);
           }
       }.start();

       mlistView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
           @Override
           public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
               ContactInfo item= (ContactInfo) madapter.getItem(position);
               Intent intent=new Intent();
               intent.putExtra("phone",item.getPhone());
               intent.putExtra("name",item.getName());
               setResult(0,intent);
               finish();
           }
       });
    }
    private void initView() {
        ((TextView)findViewById(R.id.tv_title)).setText("新建联系人");
        findViewById(R.id.rl_titlebar).setBackgroundColor(getResources().getColor(R.color.bright_purple));
        mLeftImagv=findViewById(R.id.imgv_leftbtn);
        mLeftImagv.setImageResource(R.drawable.back);
        mlistView=findViewById(R.id.lv_contact);
    }
}
